import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import iView from 'iview'

import {
  // setToken,
  getToken,
  // canTurnTo,
  setTitle,
  getTagsList,
  initRouterNode
  // getNewTagList
  // getMenuListFromLocalStorage
} from '@/libs/util'
// import config from '@/config'
import Main from '@/components/main'

import {
  // login,
  appRouter,
  dashboard
  // routes
} from '@/router/routers'

// const { homeName } = config

Vue.use(Router)

const getLocalRouter = () => {
  let localM = store.state.menu.menuList

  if (localM[0] && localM[0]['NAME'] === 'home') {
    localM.shift()
  }
  let routers = initRouterNode(localM)
  // console.log('getLocalRouter', routers, routers.length)

  let homeR =
    {
      path: '/',
      name: '_home',
      redirect: '/home',
      component: Main,
      meta: {
        hideInMenu: true,
        hideInBread: true
      },
      children: []
    }

  if (routers.length > 0) {
    homeR['children'] = [dashboard, ...routers]
    // console.log('本地有menulist', routers)
    const tagList = getTagsList(routers)
    // console.log(menulist, tagList)
    // router.addRoutes(routers)

    store.commit('setTagsList', tagList)
    store.commit('addRouters', routers)
  }
  return homeR
}

let localRouter = getLocalRouter()

// let configRouters = appRouter || []
if (localRouter && getToken()) {
  // console.log(appRouter)
  appRouter.push(localRouter)
}
// console.log(appRouter)

// console.log('appRouter', appRouter)
// 路由配置
const RouterConfig = {
  // mode: 'history',
  routes: [
    // login,
    // homeRouter,
    ...appRouter
    // ...store.state.app.routers,
    // ...localRouter,
    // ...configRouters,
    // router404
  ]
}

const router = new Router(RouterConfig)
const LOGIN_PAGE_NAME = 'login'

// const turnTo = (to, access, next) => {
//   if (canTurnTo(to.name, access, routes)) next()
//   // 有权限，可访问
//   else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
// }
// console.log(turnTo)

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()

  // console.log('router beforeEach', from, to, router.options.routes)
  if (to.name === LOGIN_PAGE_NAME) {
    if (getToken()) {
      // console.log('访问登录页 用户已登录 所以直接去主页', to.name, to.path)
      next({ replace: true, name: 'home' })
    } else {
      // console.log('访问登录页 用户未登录 继续去登陆页', to.name, to.path)
      next()
    }
  } else {
    if (getToken()) {
      // console.log('访问非登录页 用户已登录 继续往下走', to.name, to.path)
      next()
    } else {
      // console.log('访问非登录页 用户未已登录 所以直接去登陆页', to.name, to.path)
      next({ replace: true, name: LOGIN_PAGE_NAME })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
